package com.waterstudio.filedownloader.ext.m3u8.app;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloadMonitor;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.util.FileDownloadLog;
import com.waterstudio.filedownloader.ext.m3u8.M3u8FileDownloader;

import java.io.File;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    //    public static final String URL = "http://hcjs2ra2rytd8v8np1q.exp.bcevod.com/mda-hegtjx8n5e8jt9zv/mda-hegtjx8n5e8jt9zv.m3u8";
//    public static final String FILE_NAME = "hegtjx8n5e8jt9zv.m3u8";
    //    public static final String URL = "https://drive.javpob.com/sprd-1098-0.mp4/kuysad.m3u8";
//    public static final String FILE_NAME = "kuysad.m3u8";
//    public static final String URL = "https://www3.laqddc.com/hls/2018/04/07/BQ2cqpyZ/playlist.m3u8";
//    public static final String FILE_NAME = "playlist.m3u8";
    public static final String URL = "https://v.redd.it/b5fdxaieg8y11/HLSPlaylist.m3u8";
    //    public static final String URL = "https://m.ok.ru/dk/video.m3u8?st.cmd=moviePlaybackRedirect&st.sig=fef12fcbe7628f3e62e725a50c8ae9d9bbc4323e&st.mq=1&st.mvid=378222676678&st.ip=210.140.66.78&st.dla=on&st.exp=1553827104342&st.hls=on&_prevCmd=movieLayer&tkn=7928";
    public static final String FILE_NAME = "reddit.m3u8";

    TextView mTvText;
    Button mTvStart;
    Button mTvPause;
    Button mTvClear;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FileDownloader.setup(this);
        FileDownloadLog.NEED_LOG = false;
        FileDownloadMonitor.setGlobalMonitor(new FileDownloadMonitor.IMonitor() {
            @Override
            public void onRequestStart(int count, boolean serial, FileDownloadListener lis) {
                if (BuildConfig.DEBUG) {
                    Log.v("FileDownloader", String.format("onRequestStart:%s", lis.getClass().getSimpleName()));
                }
            }

            @Override
            public void onRequestStart(BaseDownloadTask task) {
                if (BuildConfig.DEBUG) {
                    Log.v("FileDownloader", String.format("onRequestStart:%s", task.getUrl()));
                }
            }

            @Override
            public void onTaskBegin(BaseDownloadTask task) {
                if (BuildConfig.DEBUG) {
                    Log.v("FileDownloader", String.format("onTaskBegin:%s", task.getUrl()));
                }
            }

            @Override
            public void onTaskStarted(BaseDownloadTask task) {
                if (BuildConfig.DEBUG) {
                    Log.v("FileDownloader", String.format("onTaskStarted:%s", task.getUrl()));
                }
            }

            @Override
            public void onTaskOver(BaseDownloadTask task) {
                if (BuildConfig.DEBUG) {
                    Log.v("FileDownloader", String.format("onTaskOver:%s", task.getUrl()));
                }
            }
        });
        mTvText = findViewById(R.id.tv_status);
        mTvStart = findViewById(R.id.btn_start);
        mTvPause = findViewById(R.id.btn_pause);
        mTvClear = findViewById(R.id.btn_clear);
        FileDownloader.getImpl().setMaxNetworkThreadCount(8);
        M3u8FileDownloader.init(new M3u8FileDownloader.Builder()
                .setRadicalMerge(true)
                .setThreadSize(4));
    }

    private File getTargetFile() {
        File file = getExternalFilesDir("Download");
        if (!file.exists()) {
            file.mkdirs();
        }
        File target = new File(file, FILE_NAME);
        return target;
    }


    public void onClickDownload(View view) {
        BaseDownloadTask downloadTask = M3u8FileDownloader.getInstance().create(URL)
                .setPath(getTargetFile().getAbsolutePath(), false);
        downloadTask.setListener(new FileDownloadLargeFileListener() {

            @Override
            protected void pending(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                mTvText.setText("pending");
            }


            @Override
            protected void started(BaseDownloadTask task) {
                super.started(task);
                mTvText.setText("started");
            }

            @Override
            protected void connected(BaseDownloadTask task, String etag, boolean isContinue, long soFarBytes, long totalBytes) {
                super.connected(task, etag, isContinue, soFarBytes, totalBytes);
                mTvText.setText("connected");
            }


            @Override
            protected void progress(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                mTvText.setText(String.format(Locale.US, "progress %d,%d", soFarBytes, totalBytes));
            }


            @Override
            protected void paused(BaseDownloadTask task, long soFarBytes, long totalBytes) {
                mTvText.setText(String.format(Locale.US, "paused %d,%d", soFarBytes, totalBytes));
            }

            @Override
            protected void completed(BaseDownloadTask task) {
                mTvText.setText(String.format(Locale.US, "complete %s", task.getTargetFilePath()));
            }


            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                e.printStackTrace();
                mTvText.setText(String.format(Locale.US, "error %s", e.getMessage()));
            }

            @Override
            protected void warn(BaseDownloadTask task) {
                mTvText.setText(String.format(Locale.US, "warn"));
            }
        });
        downloadTask.start();
    }

    public void onClickPause(View view) {
        M3u8FileDownloader.getInstance().pause(URL, getTargetFile().getAbsolutePath());
    }

    public void onClickClear(View view) {
        M3u8FileDownloader.getInstance().clearData(URL, getTargetFile().getAbsolutePath());
    }
}
